package member.order.util;

import m.system.RuntimeData;
import m.system.db.TransactionManager;
import m.system.util.DateUtil;
import m.system.util.SystemUtil;
import member.base.service.PageService;
import member.order.service.OrderCollectService;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.locks.LockSupport;

public class OrderCollectUtil implements Runnable {
    private OrderCollectUtil(){}
    private static boolean isRun=true;
    static Thread th;
    static final List<String> list=new ArrayList<>();

    @Override
    public void run() {
        while (true){
            if(list.isEmpty()){
                TransactionManager.closeConnection();
                LockSupport.park();
                TransactionManager.initConnection();
            }
            if(!isRun) break;
            if(!list.isEmpty()){
                String key=list.remove(0);
                try {
                    String[] arr=key.split(",");
                    RuntimeData.getService(OrderCollectService.class).update(arr[0],arr[1]);
                    //清除首页统计缓存
                    RuntimeData.getService(PageService.class).clearMonth(arr[0]);
                } catch (Exception e) {
                    SystemUtil.println("更新订单汇总失败：",e.getMessage(),key);
                }
            }
        }
    }
    /**
     * 添加
     */
    public static void add(String storeOid, Date accountDate){
        String key=storeOid+","+DateUtil.format(accountDate,"yyyy-MM-dd");
        if(!list.contains(key)) list.add(key);
    }

    /**
     * 开始
     */
    public static void start(){
        try {
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        if(null==th){
            th=new Thread(new OrderCollectUtil());
            th.start();
        }else{
            LockSupport.unpark(th);
        }
    }

    public static void close(){
        isRun=false;
        LockSupport.unpark(th);
    }
}
